package com.yubest.servletjsp.dao;

import com.yubest.servletjsp.model.UserInfo;
import com.yubest.servletjsp.util.SqlExecutor;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author hweiyu
 * @Description
 * @Date 2022/9/1 14:51
 */
public class UserInfoDao {

    public void add(UserInfo entity) {
        String sql = "INSERT INTO `t_user_info`(`phone`, `user_name`, `password`) VALUES (?, ?, ?)";
        SqlExecutor.insert(sql, entity.getPhone(), entity.getUserName(), entity.getPassword());
    }

    public void delete(Integer id) {
        String sql = "delete from t_user_info where id = ?";
        SqlExecutor.delete(sql, id);
    }

    public void updateById(UserInfo entity) {
        String sql = "UPDATE `t_user_info` SET `phone` = ?, `user_name` = ?, `password` = ? WHERE `id` = ?";
        SqlExecutor.update(sql, entity.getPhone(), entity.getUserName(), entity.getPassword(), entity.getId());
    }

    public List<UserInfo> queryAll() {
        List<UserInfo> result = new ArrayList<>();
        List<Map<String, Object>> list = SqlExecutor.select("select * from t_user_info");
        for (Map<String, Object> map : list) {
            UserInfo entity = new UserInfo();
            entity.setId((Integer) map.get("id"));
            entity.setPhone((String) map.get("phone"));
            entity.setUserName((String) map.get("user_name"));
            entity.setPassword((String) map.get("password"));
            result.add(entity);
        }
        return result;
    }

    public UserInfo queryByUsername(String username) {
        String sql = "select * from t_user_info where user_name = ?";
        Map<String, Object> map = SqlExecutor.selectOne(sql, username);
        if (null != map) {
            UserInfo entity = new UserInfo();
            entity.setId((Integer) map.get("id"));
            entity.setPhone((String) map.get("phone"));
            entity.setUserName((String) map.get("user_name"));
            entity.setPassword((String) map.get("password"));
            return entity;
        }
        return null;
    }

    public UserInfo queryById(Integer id) {
        String sql = "select * from t_user_info where id = ?";
        Map<String, Object> map = SqlExecutor.selectOne(sql, id);
        if (null != map) {
            UserInfo entity = new UserInfo();
            entity.setId((Integer) map.get("id"));
            entity.setPhone((String) map.get("phone"));
            entity.setUserName((String) map.get("user_name"));
            entity.setPassword((String) map.get("password"));
            return entity;
        }
        return null;
    }
}
